package com.jar.exercise.网络编程.TCP连接.客服端和服务端;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 例子：复制文件，图片不能用字符流
 * 客户端发送文件到服务器，服务器下载到本地，并返回发送成功到客户端
 * 难点：中间有一个结束标记，socket.shutdownOutput();
 */
class Server1 {

	public static void main(String[] args) throws IOException {
		ServerSocket serverSocket = new ServerSocket(12000);
		Socket socket = serverSocket.accept();
		//创建一个读取文件的字符缓冲流
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		//创建一个字符缓冲流
		PrintWriter pw = new PrintWriter(new FileWriter("d:/aaa.txt"), true);
		//创建一个输出流，返回信息给客户端
		PrintWriter bw = new PrintWriter(socket.getOutputStream(), true);
		String line;
		while ((line = br.readLine()) != null) {
			pw.println(line);
		}
		bw.println("上传成功");
		pw.close();
		socket.close();
		serverSocket.close();
	}
}

class Client1 {
	public static void main(String[] args) throws IOException {
		//创建连接
		Socket socket = new Socket("192.168.234.1", 12000);
		//获取文件对象
		File file = new File("d:/虚拟机软件.txt");
		//创建一个读取文件的字符缓冲流
		BufferedReader br = new BufferedReader(new FileReader(file));
		//创建一个写入文件的socket流
		PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);

		String line;
		while ((line = br.readLine()) != null) {
			//写到socket流
			pw.println(line);
		}
		socket.shutdownOutput();
		//创建一个输出流，返回信息给客户端
		BufferedReader bw = new BufferedReader(new InputStreamReader(socket.getInputStream()));

		System.out.println(bw.readLine());
		br.close();
		socket.close();
	}

}
